<template>
  <div class="checkout-container">
    <Header/>
    <div class="checkout-content">
      <h2 class="checkout-title">确认订单</h2>

      <!-- 课程信息 -->
      <div class="course-info">
        <div class="course-item" v-for="course in courseList" :key="course.id">
          <img :src="course.image" :alt="course.name" class="course-image">
          <div class="course-detail">
            <h3>{{ course.name }}</h3>
            <p class="validity">有效期：{{ course.validity }}</p>
          </div>
          <div class="course-price">¥{{ course.price }}</div>
        </div>
      </div>

      <!-- 支付方式 -->
      <div class="payment-method">
        <h3>支付方式</h3>
        <div class="payment-options">
          <label class="payment-option">
            <input type="radio" v-model="paymentMethod" value="alipay">
            <img src="../assets/alipay.png" alt="支付宝" class="payment-icon">
            <span>支付宝</span>
          </label>
          <label class="payment-option">
            <input type="radio" v-model="paymentMethod" value="wechat">
            <img src="../assets/wechat.png" alt="微信支付" class="payment-icon">
            <span>微信支付</span>
          </label>
        </div>
      </div>

      <!-- 优惠券 -->
      <div class="coupon-section">
        <h3>优惠券</h3>
        <select v-model="selectedCoupon" class="coupon-select">
          <option value="">不使用优惠券</option>
          <option v-for="coupon in coupons" :key="coupon.id" :value="coupon.id">
            {{ coupon.name }}
          </option>
        </select>
      </div>

      <!-- 价格信息 -->
      <div class="price-summary">
        <div class="price-item">
          <span>商品总额</span>
          <span class="amount">¥{{ totalPrice }}</span>
        </div>
        <div class="price-item">
          <span>优惠券</span>
          <span class="discount">-¥{{ couponAmount }}</span>
        </div>
        <div class="price-item total">
          <span>实付金额</span>
          <span class="final-price">¥{{ totalPrice }}</span>
        </div>
      </div>

      <!-- 服务协议 -->
      <div class="agreement">
        <label>
          <input type="checkbox" v-model="agreementChecked">
          <span>我已阅读并同意</span>
          <a href="#" class="agreement-link">《服务协议》</a>
        </label>
      </div>

      <!-- 支付按钮 -->
      <div class="checkout-action">
        <button
            class="pay-button"
            :disabled="!agreementChecked || !paymentMethod"
            @click="handlePayment"
        >
          立即支付
        </button>
      </div>
    </div>


    <WxPayModal
        v-model:visible="showWXPayModal"
        :payUrl="wxPayUrl"
        :totalFee="total_fee"/>
  </div>
</template>

<script setup>
import {ref, computed, onMounted, onUnmounted} from 'vue'
import Header from '../components/Header.vue'
import {useRouter, useRoute} from "vue-router";
import {ElMessage} from "element-plus";
import axios from "axios";
import WxPayModal from "../components/WxPayModal.vue";

const router = useRouter()
const route = useRoute()

const showWXPayModal = ref(false)

const wxPayUrl = ref('')

const orderNumber = ref('')

const total_fee = ref(0)

const totalPrice = ref(0)

const courseList = ref([])

// 课程信息
const course = ref({
  name: 'Python全栈开发工程师',
  image: 'https://img30.360buyimg.com/jdcms/s480x480_jfs/t1/305399/38/704/166022/68201216Ff6510ba5/919edbaa90b03b77.jpg.avif',
  validity: '永久有效',
  price: 2999.00
})

// 支付方式
const paymentMethod = ref('alipay')

// 优惠券
const coupons = ref([])
const selectedCoupon = ref('')
const couponAmount = ref(0)

// 最终价格
const finalPrice = computed(() => {
  return (course.value.price - couponAmount.value).toFixed(2)
})

// 服务协议
const agreementChecked = ref(false)


// 建议放在模块顶部（组件外部作用域），保证一次“下单尝试”期间可复用同一个幂等键
let currentIdempotencyKey = null;

function generateIdempotencyKey() {
  if (window.crypto && crypto.randomUUID) {
    return crypto.randomUUID();
  }
  return 'key-' + Math.random().toString(36).slice(2) + Date.now();
}

function sleep(ms) {
  return new Promise((res) => setTimeout(res, ms));
}

/**
 * 思路讲解
 * 生成并复用幂等键：一次点击“提交订单”开始到结束，始终用同一个 Idempotency-Key；这样重试/刷新 token 都不会产生新订单。
 * 429 重试策略：服务端提示“正在创建”时，用指数退避重试，减少无意义压力，同时等待缓存命中返回首次结果。
 * 401 刷新：刷新 token 后继续调用同一次下单，依然使用同一个幂等键，确保不会重复创建。
 * 参数规范：use_coupon 改为布尔值，price/total_price 强制转数值；后端也会校验价格与课程状态。
 * 错误处理：尽量给出清晰的用户提示；登录过期引导到登录页。
 * 这样改完后，你的前端即可与后端“幂等 + 分布式锁 + DB 兜底”的设计配合良好，避免重复下单且更健壮地处理网络/服务端波动。
 * @returns {Promise<void>}
 */
// 处理支付
const handlePayment = async () => {
  if (!agreementChecked.value) {
    ElMessage.warning('请先同意服务协议');
    return;
  }
  if (!paymentMethod.value) {
    ElMessage.warning('请选择支付方式');
    return;
  }

  // 读取 token
  let token = localStorage.getItem('token') || sessionStorage.getItem('token');
  if (!token) {
    ElMessage.warning('请先登录');
    router.push('/login');
    return;
  }

  if(orderNumber.value){
    await createWxPayment(orderNumber.value)
    return
  }

  // 一次“下单尝试”只生成一次幂等键；后续重试/刷新 token 都复用这个键
  currentIdempotencyKey = currentIdempotencyKey || generateIdempotencyKey();

  // 安全解析路由里的课程信息（避免 JSON.parse 报错影响流程）
  let routeCourses = [];
  try {
    // 你的原始代码中 route.query.courses 是 JSON 字符串
    routeCourses = JSON.parse(route.query.courses || '[]');
  } catch (e) {
    routeCourses = [];
  }

  const orderParams = {
    courseList: courseList.value.map((course) => {
      const courseInfo = routeCourses.find((info) => info.courseId == course.id) || {};
      return {
        course_id: course.id,
        expire_time: courseInfo.validityId,      // 0=永久；否则为天数
        price: Number(course.price),             // 强制转数值
        expire_text: courseInfo.validityText
      };
    }),
    pay_method: paymentMethod.value == 'alipay' ? 1 : 2,
    use_coupon: false,       // 用布尔值更语义化；是否使用优惠券
    use_coupon_id: null,     // 如有具体优惠券，传其ID
    total_price: Number(totalPrice.value),
    real_price: Number(totalPrice.value)
  };

  // 429 指数退避重试参数
  const maxRetries = 3;
  const baseDelayMs = 600;
  let attempt = 0;

  try {
    // 用循环显式处理 429 和 401 场景
    // - 429：订单正在创建中 → 指数退避后重试（复用同一个幂等键）
    // - 401：刷新 token 后，带新 token 继续重试（仍然复用同一个幂等键）
    // - 其他错误：提示并退出
    for (; ;) {
      console.log("---000000")
      try {
        const res = await axios.post('http://localhost:8000/orders/create/', orderParams, {
          headers: {
            'Authorization': 'Bearer ' + token,
            'Content-Type': 'application/json',
            'Idempotency-Key': currentIdempotencyKey
          }
        });
        console.log(res.data)

        if (res.data.code == 1) {
          ElMessage.success('订单创建成功');
          const order_number = res.data.data.order_number
          if (paymentMethod.value == 'wechat') {
            console.log('微信支付')
            console.log('order_number:' + order_number)
            await createWxPayment(order_number)
          }
          // TODO: 跳转支付/订单详情
          // router.push({ name: 'Pay', query: { out_trade_no: res.data.data.order_number } });
        } else {
          ElMessage.error(res.data.message || '订单创建失败');
        }
        break; // 成功/业务返回后跳出循环
      } catch (error) {
        const status = error && error.response && error.response.status;

        // 401：刷新 token 后继续重试（复用幂等键，不会重复下单）
        if (status === 401) {
          try {
            const newToken = await refreshToken(); // 注意这里需要()调用
            token = newToken;                      // 更新本地 token 后继续循环
            continue;
          } catch (e) {
            ElMessage.error('登录已过期， 请重新登录');
            localStorage.removeItem('token');
            localStorage.removeItem('refresh_token');
            sessionStorage.removeItem('token');
            sessionStorage.removeItem('refresh_token');
            router.push('/login');
            break;
          }
        }

        // 429：服务端正在创建中，指数退避后重试（复用相同幂等键）
        if (status === 429 && attempt < maxRetries) {
          const delay = baseDelayMs * Math.pow(2, attempt); // 600/1200/2400ms...
          attempt += 1;
          await sleep(delay);
          continue;
        }

        // 其他错误：提示并退出
        const msg =
            (error && error.response && error.response.data && error.response.data.message) ||
            error.message ||
            '下单失败';
        ElMessage.error(msg);
        break;
      }
    }
  } finally {
    // 一次尝试结束（成功或最终失败）后清空幂等键；下一次点击会生成新键
    currentIdempotencyKey = null;
  }
};
// // 处理支付
// const handlePayment = async () => {
//   if (!agreementChecked.value) {
//     ElMessage.warning('请先同意服务协议')
//     return
//   }
//   if (!paymentMethod.value) {
//     ElMessage.warning('请选择支付方式')
//     return
//   }
//   // TODO: 实现支付逻辑
//   const token = localStorage.getItem("token") || sessionStorage.getItem("token")
//   if (!token) {
//     ElMessage.warning("请先登录")
//     router.push("/login")
//     return
//   }
//
//   try {
//
//
//     const orderParams = {
//       "courseList": courseList.value.map(course => {
//         const courseInfo = JSON.parse(route.query.courses).find(info => info.courseId == course.id)
//         return {
//           course_id: course.id,
//           expire_time: courseInfo.validityId,
//           price: course.price,
//           expire_text: courseInfo.validityText
//         }
//
//       }),
//       "pay_method": paymentMethod.value == 'alipay' ? 1 : 2,
//       "use_coupon": 0,
//       "total_price": Number(totalPrice.value),
//       "real_price": Number(totalPrice.value)
//     }
//
//     const res = await axios.post("http://localhost:8000/orders/create/", orderParams, {
//       headers: {
//         "Authorization": "Bearer " + token
//       }
//     })
//
//     if (res.data.code == 1) {
//       ElMessage.success("订单创建成功")
//     } else {
//       ElMessage.error(res.data.message || "订单创建失败")
//     }
//   } catch (error) {
//     if (error.response.status == 401) {
//       try {
//         const newToken = await refreshToken
//         await handlePayment(newToken)
//       } catch (error) {
//         ElMessage.error("登录已过期， 请重新登录")
//         localStorage.removeItem('token')
//         localStorage.removeItem('refresh_token')
//         sessionStorage.removeItem('token')
//         sessionStorage.removeItem('refresh_token')
//         router.push("/login")
//       }
//     }
//   }
// }
// const handlePayment = () => {
//   if (!agreementChecked.value) {
//     ElMessage.warning('请先同意服务协议')
//     return
//   }
//   if (!paymentMethod.value) {
//     ElMessage.warning('请选择支付方式')
//     return
//   }
//   // TODO: 实现支付逻辑
// }


const createWxPayment = async (order_number) => {

  console.log(order_number)
  try {
    const token = localStorage.getItem('token') || sessionStorage.getItem('token')
    const res = await axios.post('http://localhost:8000/payments/wx/create/', {
      "order_number": order_number
    }, {
      headers: {
        Authorization: `Bearer ${token}`
      }
    })

    console.log(res)

    if (res.data.code == 1) {
      console.log("================")
      console.log(res.data.data.pay_url)
      //二维码链接==》二维码
      wxPayUrl.value = res.data.data.pay_url
      total_fee.value = res.data.data.total_fee
      orderNumber.value = res.data.data.order_number
      showWXPayModal.value = true

      //开始轮询支付状态

      startPollingPaymentStatus(orderNumber.value, res.data.data.pay_order_number)

    }
  } catch (error) {

  }


}


// 轮询间隔（毫秒）
const POLLING_INTERVAL = 3000
let pollingTimer = null

// 开始轮询支付状态
const startPollingPaymentStatus = (orderNumber, payOrderNumber) => {
  // 清除可能存在的之前的轮询
  if (pollingTimer) {
    clearInterval(pollingTimer)
  }

  // 设置轮询
  pollingTimer = setInterval(async () => {
    try {
      const token = localStorage.getItem('token') || sessionStorage.getItem('token')
      const response = await axios.get(
          `http://127.0.0.1:8000/payments/wx/query/?order_number=${orderNumber}&pay_order_number=${payOrderNumber}`,
          {
            headers: {
              'Authorization': `Bearer ${token}`
            }
          }
      )

      console.log(response)

      if (response.data.code == 1) {
        // 支付成功，停止轮询
        clearInterval(pollingTimer)
        showWXPayModal.value = false
        ElMessage.success('支付成功')
        // 跳转到支付成功页面
        router.push({
          path: '/pay-success',
          query: {
            orderNumber: orderNumber
          }
        })
      }
    } catch (error) {
      console.error('查询支付状态失败:', error)
    }
  }, POLLING_INTERVAL)
}

// 在组件卸载时清除轮询
onUnmounted(() => {
  if (pollingTimer) {
    clearInterval(pollingTimer)
  }
})

// 关闭支付弹窗时清除轮询
const handleCloseWxPayModal = () => {
  showWXPayModal.value = false
  if (pollingTimer) {
    clearInterval(pollingTimer)
  }
}

const refreshToken = async () => {
  try {
    const refreshToken = localStorage.getItem('refresh_token') || sessionStorage.getItem('refresh_token')
    if (!refreshToken) {
      throw new Error('No refresh token')
    }

    const response = await axios.post('http://127.0.0.1:8000/jwt/refresh/', {
      refresh: refreshToken
    })

    if (response.data.access) {
      // 更新access token
      const newToken = response.data.access
      localStorage.setItem('token', newToken)
      sessionStorage.setItem('token', newToken)
      return newToken
    }
    throw new Error('Failed to refresh token')
  } catch (error) {
    console.error('刷新token失败:', error)
    throw error
  }
}


const fetchCartData = async (token) => {
  try {
    const res = await axios.get("http://127.0.0.1:8000/cart/", {
      headers: {
        "Authorization": "Bearer " + token
      }
    })

    if (res.data.code == 1) {
      const coursesP = route.query.courses
      console.log(coursesP)

      const selectedCourseInfo = JSON.parse(coursesP)
      console.log(selectedCourseInfo)


      const selectedCartInfo = res.data.data.cart_list.filter(item => item.is_selected == 1)
      console.log(selectedCartInfo)
      if (!selectedCartInfo || selectedCartInfo.length == 0) {
        router.push("/")
      }

      selectedCartInfo.map(item => {
        const courseInfo = selectedCourseInfo.find(info => info.courseId == item.id)
        const mydata = {}
        mydata.id = item.id
        mydata.name = item.name
        mydata.validity = courseInfo.validityText
        mydata.price = courseInfo.price
        mydata.image = item.course_img
        courseList.value.push(mydata)

      })


      totalPrice.value = courseList.value.reduce((sum, course) => sum + course.price, 0).toFixed(2)
    } else {
      console.log("=================")
      console.log(res.data.message)
      if (res.data.message == "购物车为空") {
        router.push("/")
      }
      ElMessage.error(res.data.message || '获取数据失败')
    }

  } catch (error) {
    if (error.response.status == 401) {
      try {

        const newToken = await refreshToken()

        return await fetchCartData(newToken)

      } catch (error) {
        ElMessage.error('登录已过期，请重新登录')
        localStorage.removeItem('token')
        localStorage.removeItem('refresh_token')
        sessionStorage.removeItem('token')
        sessionStorage.removeItem('refresh_token')


        router.push('/login')
      }
    } else {
      ElMessage.error('网络错误')
    }

  }

}


const initCheckOut = async () => {
  const token = localStorage.getItem('token') || sessionStorage.getItem('token')
  if (!token) {
    ElMessage.warning('请先登录')
    router.push('/login')
    return
  }

  await fetchCartData(token)

}

onMounted(() => {

  initCheckOut()

})
</script>

<style scoped>
.checkout-container {
  min-height: 100vh;
  background-color: #f5f5f5;
}

.checkout-content {
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
}

.checkout-title {
  font-size: 24px;
  color: #333;
  margin-bottom: 20px;
}

.course-info {
  background: #fff;
  border-radius: 8px;
  padding: 20px;
  margin-bottom: 20px;
}

.course-item {
  display: flex;
  align-items: center;
  gap: 20px;
}

.course-image {
  width: 120px;
  height: 80px;
  object-fit: cover;
  border-radius: 4px;
}

.course-detail h3 {
  margin: 0 0 10px;
  font-size: 16px;
  color: #333;
}

.validity {
  color: #666;
  font-size: 14px;
  margin: 0;
}

.course-price {
  margin-left: auto;
  color: #ff6b00;
  font-size: 18px;
  font-weight: bold;
}

.payment-method {
  background: #fff;
  border-radius: 8px;
  padding: 20px;
  margin-bottom: 20px;
}

.payment-method h3 {
  margin: 0 0 15px;
  font-size: 16px;
  color: #333;
}

.payment-options {
  display: flex;
  gap: 20px;
}

.payment-option {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 10px 20px;
  border: 1px solid #e8e8e8;
  border-radius: 4px;
  cursor: pointer;
}

.payment-option:hover {
  border-color: #ff6b00;
}

.payment-icon {
  width: 24px;
  height: 24px;
}

.coupon-section {
  background: #fff;
  border-radius: 8px;
  padding: 20px;
  margin-bottom: 20px;
}

.coupon-section h3 {
  margin: 0 0 15px;
  font-size: 16px;
  color: #333;
}

.coupon-select {
  width: 100%;
  padding: 10px;
  border: 1px solid #e8e8e8;
  border-radius: 4px;
  font-size: 14px;
}

.price-summary {
  background: #fff;
  border-radius: 8px;
  padding: 20px;
  margin-bottom: 20px;
}

.price-item {
  display: flex;
  justify-content: space-between;
  margin-bottom: 10px;
  color: #666;
}

.price-item.total {
  border-top: 1px solid #e8e8e8;
  padding-top: 10px;
  margin-top: 10px;
  color: #333;
}

.amount {
  color: #333;
}

.discount {
  color: #52c41a;
}

.final-price {
  color: #ff6b00;
  font-size: 20px;
  font-weight: bold;
}

.agreement {
  text-align: center;
  margin-bottom: 20px;
}

.agreement-link {
  color: #1890ff;
  text-decoration: none;
}

.agreement-link:hover {
  text-decoration: underline;
}

.checkout-action {
  text-align: center;
}

.pay-button {
  padding: 12px 40px;
  font-size: 16px;
  color: #fff;
  background: #ff6b00;
  border: none;
  border-radius: 24px;
  cursor: pointer;
  transition: all 0.3s;
}

.pay-button:hover {
  background: #ff7b00;
}

.pay-button:disabled {
  background: #ccc;
  cursor: not-allowed;
}
</style>